<template>
  <Dialog v-model="dialogVisible" :title="dialogTitle" width="520px">
    <el-form ref="formRef" v-loading="formLoading" :model="formData" :rules="rules" label-width="80">
      <el-form-item label="选择线路" prop="routId">
        <el-select clearable v-model="formData.routId" :disabled="disabled" filterable placeholder="请选择线路"
          class="!w-200px">
          <el-option v-for="item in lineList" :key="item.id" :label="item.routeName" :value="item.id" />
        </el-select>
      </el-form-item>
    </el-form>
    <el-table v-loading="loading" :data="list" border stripe
      :header-cell-style="{ background: '#F3F4F7', color: '#555' }">
      <el-table-column label="车牌号" align="center" prop="vehicleNo" min-width="100" :show-overflow-tooltip="true" />
      <el-table-column label="司机姓名" align="center" prop="driverName" min-width="100" :show-overflow-tooltip="true" />
      <el-table-column label="司机电话" align="center" prop="driverPhone" min-width="100" :show-overflow-tooltip="true" />
    </el-table>
    <template #footer>
      <el-button :disabled="formLoading" type="primary" @click="submitForm">确认提交</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script lang="ts" setup>
  import { cloneDeep } from 'lodash'
  import { getTenantId } from '@/utils/auth'
  import { DICT_TYPE, getIntDictOptions } from '@/utils/dict'
  import * as goodsSourceApi from '@/api/transportation/goodsSource'

  const dialogTitle = ref('添加车辆')
  const message = useMessage()
  const dialogVisible = ref(false)
  const formLoading = ref(false)
  const loading = ref(false)
  const formRef = ref()
  const formData = ref({
    routId: undefined
  })
  const lineList = ref([])
  const list = ref([])

  const rules = reactive({
    routId: [{ required: true, message: '请选择线路', trigger: 'change' }]
  })

  const open = async (result) => {
    dialogVisible.value = true
    formData.value.routId = undefined
    list.value = result
    getLineList()
  }

  const getLineList = async () => {
    const res = await goodsSourceApi.getLineList()
    lineList.value = res || []
  }

  const submitForm = async () => {
    const valid = await formRef.value.validate()
    if (!valid) return
    try {
      formLoading.value = true
      const data = cloneDeep(formData.value)
      data['vehicleDriverList'] = list.value
      await goodsSourceApi.bindVehicles(data)
      message.success('操作成功')
      dialogVisible.value = false
    } finally {
      formLoading.value = false
    }
  }

  defineExpose({ open })
</script>